import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { MonthWorkService } from './monthwork.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';

@Component({
    selector: 'app-monthwork-table',
    templateUrl: './monthwork.table.component.html',
    styleUrls: ['./monthworkarea.component.less'],
})
export class MonthworkTableComponent implements OnInit {
    pageIndex: any = 1;
    pageSize = '50';
    pageTotal: any = '';
    queryData: any = {};
    tableData: any = [];
    yearVisible = false;
    yearLoading = false;
    addData: any = [];
    optConfig: any = {}
    statusList: any = {};
    lockHeadScroll = { y: window.innerHeight - 350 + 'px' };
    headBarCfg = {
        gq: {
            tab1: ['add', 'tibao', 'delete']
        },
        cj: {
            tab1: ['add', 'tibao', 'delete'],
            tab2: ['pizhun', 'bohui'],
        },
        gcs: {
            tab1: ['add', 'tibao', 'delete'],
            tab2: ['pizhun', 'bohui'],
            tab3: [],
        },
        jskz: {
            tab1: ['pizhun', 'bohui'],
            tab2: ['pizhun', 'bohui'],
            tab3: [],
        },
        dz: {
            tab1: ['pizhun', 'bohui'],
            tab2: ['pizhun', 'bohui'],
            tab3: [],
        },
        qzbh: {
            tab1: ['qzbohui'],
            tab2: ['qzbohui'],
            tab3: ['qzbohui'],
        },
    };


    queryCfg = {
        gq: {
            tab1: []
        },
        cj: {
            tab1: [],
            tab2: ['cjSelect']
        },
        gcs: {
            tab1: [],
            tab2: ['cjSelect'],
            tab3: ['gqSelect'],
        },
        jskz: {
            tab1: [],
            tab2: ['cjSelect'],
            tab3: ['gqSelect'],
        },
        dz: {
            tab1: [],
            tab2: ['cjSelect'],
            tab3: ['gqSelect'],
        },
        qzbh: {
            tab1: [],
            tab2: ['cjSelect'],
            tab3: ['gqSelect'],
        },
    };
    spztList = [
        { "opValue": "0", "opName": "编辑" },
        { "opValue": "1", "opName": "提交" },
        { "opValue": "2", "opName": "车间批准" },
        { "opValue": "3", "opName": "车间驳回" },
        { "opValue": "4", "opName": "段批准" },
        { "opValue": "5", "opName": "段驳回" }
    ];
    wsNote = '';
    userInfo = JSON.parse(this.ls.get('loginInfo'));
    gqList = [];
    cjList = [];

    statusYearVisible = false;
    statusYearNid = '';
    // isTj = '';
    @Input()
    set inputParam(v) {
        if (!v) {
            return;
        }
        Object.assign(this.queryData, v);
        if (v.page) {
            this.pageIndex = v.page;
        }
        if (v.rows) {
            this.pageSize = v.rows;
        }
        // if (v.isTj === 'tj') {
        //     this.isTj = v.isTj;
        //     delete this.queryData.isTj;
        // }
        // if (v.isTj === 'tj') {
        //     this.queryTj();
        // } else {
        // }
        this.query();
    };

    @Input()
    user: { userType, tab };

    @Output()
    dbclick = new EventEmitter();

    ngOnInit(): void {
        this.initOptConfig();
        this.initStatusList();
        // if (this.queryCmpShowCheck('cjSelect')) {
        this.getCj();
        // }
        if (this.queryCmpShowCheck('gqSelect')) {
            this.getGq();
        }
    }

    constructor(
        private monthWorkService: MonthWorkService,
        private message: NzMessageService,
        private modalService: NzModalService,
        private ls: LocalStorage,
    ) { }

    initStatusList() {
        if (['gcs', 'jskz', 'dz', 'qzbh'].includes(this.user.userType) && this.user.tab === 1) {
            this.statusList = {
                '0': '科员修改中',
                '1': '科员已提报',
                '2': '科长已批准',
                '3': '科长已驳回',
                '4': '领导已批准',
                '5': '领导已驳回',
            };
        } else {
            this.statusList = {
                '0': '修改中',
                '1': '已提报',
                '3': '已驳回',
                '4': '已批准',
            };
        }
    }

    initOptConfig() {
        const deleteCfg = {
            name: '删除',
            value: ['0', '3'],
            optfunc: this._optFunc_delete,
        };
        const tibaoCfg: any = {
            name: '提报',
            value: ['0', '3'],
            optfunc: this._optFunc_tibao
        };
        const pizhunCfg: any = {
            name: '批准',
            // value: ['1'],
            optfunc: this._optFunc_pizhun
        };
        const bohuiCfg: any = {
            name: '驳回',
            // value: ['1'],
            optfunc: this._optFunc_bohui
        };
        const qzbohuiCfg: any = {
            name: '强制驳回',
            value: ['4'],
            // value: ['1', '5'],
            optfunc: this._optFunc_bohui
        };
        if (this.user.tab === 1) {
            // 段领导只能批准驳回技术科员的提报，所以肯定使用段级状态
            if (['jskz', 'dz'].includes(this.user.userType)) {
                pizhunCfg.value = ['1', '5'];
                bohuiCfg.value = ['1', '5'];
            } else {
                pizhunCfg.value = ['1'];
                bohuiCfg.value = ['1'];
            }

            switch (this.user.userType) {
                case 'jskz':
                    pizhunCfg.value = ['1', '5'];
                    bohuiCfg.value = ['1', '5'];
                    break;
                case 'dz':
                    pizhunCfg.value = ['2'];
                    bohuiCfg.value = ['2'];
                    break;
                default:
                    pizhunCfg.value = ['1'];
                    bohuiCfg.value = ['1'];
                    break;
            }
        } else if (this.user.tab === 2) {
            switch (this.user.userType) {
                case 'gcs':
                    pizhunCfg.value = ['1', '8'];
                    bohuiCfg.value = ['1', '8'];
                    break;
                case 'jskz':
                    pizhunCfg.value = ['2', '5'];
                    bohuiCfg.value = ['2', '5'];
                    break;
                case 'dz':
                    pizhunCfg.value = ['7'];
                    bohuiCfg.value = ['7'];
                    break;
                default:
                    break;
            }
        }

        this.optConfig = {
            'delete': deleteCfg,
            'tibao': tibaoCfg,
            'pizhun': pizhunCfg,
            'bohui': bohuiCfg,
            'qzbohui': qzbohuiCfg,
        }
    }

    btnShowCheck(btnType) {
        if (this.user.userType && this.user.tab) {
            return this.headBarCfg[this.user.userType]['tab' + this.user.tab].includes(btnType);
        } else {
            return '';
        }
    }

    queryCmpShowCheck(cmpType) {
        if (this.user.userType && this.user.tab) {
            return this.queryCfg[this.user.userType]['tab' + this.user.tab].includes(cmpType);
        } else {
            return '';
        }
    }

    readyload(page, size) {
        this.pageIndex = page;
        this.pageSize = size;
        this.query();
    }

    // 第一页列表数据
    query() {

        const param: any = {
            page: this.pageIndex,
            rows: this.pageSize,
        };
        Object.assign(param, this.queryData);
        // if (this.user && this.user.userType === 'cj' && this.user.tab === 2) {
        //     param.gqorg = this.queryData.gqorg || '';
        // }
        // if (this.user && ['gcs', 'jskz', 'dz'].includes(this.user.userType) && this.user.tab === 3) {
        //     param.cjorg = this.queryData.cjorg || '';
        // }
        if (this.queryData.ym) {
            const ym = this.getYm(this.queryData.ym);
            param.nyear = ym[0] + '';
            param.nmonth = ym[1] + '';
        }
        if (!param.cjorg) {
            delete (param.cjorg);
        }
        if (!param.ym) {
            delete (param.ym);
        }
        if (param.orgtype === 'qzbh') {
            param.orgtype = 'dz';
        }
        this.monthWorkService.query(param).subscribe((res) => {
            if (res.type === 'success') {
                this.tableData = res.data.rows;
                if (this.tableData) {
                    this.pageTotal = res.data.total;
                }
            }
        })
    }

    // 第一页列表数据
    queryTj() {

        const param: any = {
            page: this.pageIndex,
            rows: this.pageSize,
        };
        Object.assign(param, this.queryData);
        if (this.queryData.ym) {
            const ym = this.getYm(this.queryData.ym);
            param.nYear = ym[0] + '';
            param.nMonth = ym[1] + '';
        }
        if (param.cjorg) {
            delete (param.cjorg);
        }
        if (param.ym) {
            delete (param.ym);
        }
        if (param.orgtype) {
            delete param.orgtype
        }
        this.monthWorkService.queryTj(param).subscribe((res) => {
            if (res.type === 'success') {
                this.tableData = res.data.rows;
                if (this.tableData) {
                    this.pageTotal = res.data.total;
                }
            }
        })
    }


    // 显示[状态]弹出层
    statusShowModal(nid) {
        this.statusYearNid = nid;
        this.statusYearVisible = true;
    }
    statusHideModal() {
        this.statusYearVisible = false;
    }
    /**
     * 获取日期中的年月
     * @param date 日期
     */
    getYm(date: Date) {
        const y = date.getFullYear();
        const m = date.getMonth() + 1;
        return [y, m]
    }
    checkAll(v) {
        this.tableData.forEach(row => {
            row.checked = v;
        });
    }

    // 显示[新编]弹出层
    addModal() {
        this.yearVisible = true;
    }

    // 保存[新编]弹出层
    addOk() {
        this.yearLoading = true;
        if (this.addData.ym) {
            const ym = this.getYm(this.addData.ym);
            const param = {
                nYear: ym[0],
                nMonth: ym[1],
            }
            this.monthWorkService.add(param).subscribe(res => {
                if (res.type === 'success') {
                    this.message.success('新增成功');
                    this.yearLoading = false;
                    this.addCancel();
                    this.query();
                } else {
                    this.message.warning('新增失败');
                }
            })
        }
    }

    // 关闭[新编]弹出层
    addCancel() {
        this.yearVisible = false;
    }

    getChecked() {
        const delRows = this.tableData.filter(row => row.checked);
        return delRows;
    }

    getGq() {
        const param = { orgId: this.queryData.cjorg || this.userInfo.VC_ORG$ID, cjandgq: 1 };
        this.monthWorkService.getgongquByCjId(param).subscribe(res => {
            this.gqList = res;
        })
    }
    getCj() {
        this.monthWorkService.getCjList().subscribe(res => {
            this.cjList = res;
        })
    }

    /**
     * 操作检验
     * @param optType 操作类型
     * @param checkedRows 勾选条目
     */
    optCheck(optType, checkedRows) {
        let check = true;
        const optName = this.optConfig[optType].name;
        if (!checkedRows.length) {
            this.message.warning(`请先勾选条目以执行 ${optName} 操作`);
            check = false;
        } else {
            const optSta = this.optConfig[optType].value;
            const index = checkedRows.findIndex(row => {
                return !optSta.includes(row.VC_STATUS);
            })
            const statusList = this.statusList;
            const qsStaStr = optSta.map(el => statusList[el]);
            if (index !== -1) {
                this.message.warning(`您只能${optName}状态为: ${qsStaStr.join('、')} 的条目，勾选项中存在不可${optName}项`,
                    { nzDuration: 5000 });
                check = false;
            }

            // if (this.selfCheck(optType, checkedRows) === false) {
            //   return false;
            // }
        }
        return check;
    }

    optAll(optType, content?) {
        const checkedRows = this.getChecked();
        const optName = this.optConfig[optType].name;
        const check = this.optCheck(optType, checkedRows);
        if (!check) {
            return;
        }
        if (content) {
            this.wsNote = '';
        }
        this.modalService.confirm({
            nzTitle: `确认${optName}勾选项？`,
            nzWidth: '600',
            nzContent: content || "",
            nzOnOk: () => {
                const obs = [];
                this.optConfig[optType].optfunc.call(this, checkedRows);
            }
        })
    }

    trDbclick(row) {
        this.dbclick.emit(row);
    }

    pageSizeChange(v) {
        this.pageSize = v;
        this.query();
    }
    pageIndexChange(v) {
        this.pageIndex = v;
        this.query();
    }

    _optFunc_delete(rows) {
        if (!rows || !rows.length) {
            return;
        }
        const ids = [];
        rows.forEach(row => {
            ids.push(row.N_ID);
        });
        if (!ids.length) {
            return;
        }
        this.monthWorkService.delete({ ids: ids.join() }).subscribe(res => {
            if (res.type === 'success') {
                this.message.success('删除成功');
                this.query();
            } else {
                this.message.warning('删除失败');
            }
        });
    }



    _optFunc_tibao(rows) {
        this._optFunc_shenpi(rows, 1, '提报');
    }
    _optFunc_bohui(rows) {
        let status;
        if (this.user.userType === 'qzbh') {
            status = 6;
        } else {
            if (this.user.tab === 1) {// dz jskz 
                status = this.user.userType === 'dz' ? 5 : 3;
            } else if (this.user.tab === 2) {
                switch (this.user.userType) {
                    case 'gcs':
                        status = 3;
                        break;
                    case 'jskz':
                        status = 8;
                        break;
                    case 'dz':
                        status = 5;
                        break;
                    default:
                        break;
                }
            } else {
                status = 3
            }
        }
        this._optFunc_shenpi(rows, status, '驳回');
    }
    _optFunc_pizhun(rows) {
        let status;
        if (this.user.tab === 1) { // dz jskz 
            status = this.user.userType === 'jskz' ? 2 : 4;
        } else if (this.user.tab === 2) {
            switch (this.user.userType) {
                case 'gcs':
                    status = 2;
                    break;
                case 'jskz':
                    status = 7;
                    break;
                case 'dz':
                    status = 4;
                    break;
                default:
                    break;
            }
        } else {
            status = 4
        }
        this._optFunc_shenpi(rows, status, '批准');
    }
    _optFunc_shenpi(rows, status, optName) {
        if (!rows || !rows.length) {
            return;
        }
        const ids = [];
        rows.forEach(row => {
            ids.push(row.N_ID);
        });
        if (!ids.length) {
            return;
        }
        const param: any = { id: ids.join(), vcStatus: status };
        if (this.wsNote) {
            if (this.user.userType === 'dz') {
                param.segNote = this.wsNote;
            } else if (this.user.userType === 'qzbh') {
                if (this.user.tab === 1) {
                    param.segNote = this.wsNote;
                } else {
                    param.wsNote = this.wsNote;
                }
            } else {
                param.wsNote = this.wsNote;
            }
        }
        return this.monthWorkService.shenpi(param).subscribe(res => {
            if (res.type === 'success') {
                this.message.success(optName + '成功');
                this.query();
            } else {
                this.message.warning(optName + '失败');
            }
        });
    }

}